<template>
	<view class="wrap">
		<view class="top">
			<view class="item">
				<view class="left">收货人</view>
				<input type="text" v-model="form.name" placeholder-class="line" placeholder="请填写收货人姓名"
					@input="validateName" />
			</view>
			<view class="error_text">{{errors.name}}</view>
			<view class="item">
				<view class="left">手机号码</view>
				<input type="text" v-model="form.phone" placeholder-class="line" placeholder="请填写收货人手机号"
					@input="validatePhone" />
			</view>
			<view class="error_text">{{errors.phone}}</view>
			<view class="item" @tap="show=true">
				<view class="left">所在地区</view>
				{{getAddressText()}}
				<u-picker keyName="name" :show="show" ref="uPicker" @cancel="pickerCancel" :columns="columns"
					@confirm="confirm" @change="changeHandler">
				</u-picker>
			</view>
			<view class="error_text">{{errors.userAddress}}</view>
			<view class="item address">
				<view class="left">详细地址</view>
				<textarea type="text" v-model="form.address" placeholder-class="line" placeholder="街道、楼牌等"
					@input="validateAddress" />
			</view>
			<view class="error_text">{{errors.address}}</view>
		</view>
		<view class="bottom">

			<view class="tag">
				<view class="left">标签</view>
				<view class="right">
					<text v-for="(tag, index) in tags" :key="index"
						:class="['tags', { active: form.selectedTags.includes(tag) }]" @click="toggleTag(tag)">
						{{ tag }}
					</text>
					<view class="tags plus">
						<u-icon size="22" name="plus"></u-icon>
					</view>
				</view>
			</view>

			<view class="addSite" @tap="addAddress">
				<view class="add">保存</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		areaList
	} from '@/common/util/address-data'

	export default {

		data() {
			return {
				tags: ['家', '公司', '学校'],
				id: 0,
				errors: { // 存储验证错误信息
					name: '',
					phone: '13616054370',
					address: '1111',
					userAddress: ''
				},
				form: {
					name: '',
					phone: '',
					address: '',
					tag: '',
					is_default: 0,
					selectedTags: [],
					city:''
				},
				show: false,
				address: '',
				getLocationState: false,
				//要提交的表单信息
				userAddress: {
					province: '福建',
					city: '厦门',
					area: '湖里'
				},
				//三级联动组件展示框
				addressShow: false,
				//省市区数据
				columns: [
					[],
					[],
					[]
				],

			};
		},
		created() {
			this.columns[0] = areaList;
			this.columns[1] = areaList[0].cities;
			this.columns[2] = areaList[0].cities[0].districts;
		},
		computed: {
			getAddressText() {
				return () => this.userAddress.province + '/' + this.userAddress.city + '/' + this.userAddress.area;
			}
		},
		onLoad(options) {
			console.log(options)
			this.id = options.id;

			//用于编辑
			if (this.id) {
				this.detailAddress()
			}

		},
		methods: {
			toggleTag(tag) {
				const index = this.form.selectedTags.indexOf(tag);
				if (index > -1) {
					// 如果标签已选中，则取消选中
					this.form.selectedTags.splice(index, 1);
				} else {
					// 如果标签未选中，则添加到 selectedTags
					this.form.selectedTags.push(tag);
				}
				//兼容数组转成字符串
				this.form.tag = this.form.selectedTags.join(","); 			
			},
			//地址详情
			async detailAddress() {
				let that = this
				let response = await this.$api.detailAddress({
					id: this.id
				})
				this.form = response.data
				//兼容字符串转换成数组
				this.form.selectedTags = this.form.tag.split(',')
				console.log(this.form)
			},
			// 实时验证姓名是否为空
			validateName(e) {
				if (!this.form.name.trim()) {
					this.errors.name = '收货人姓名不能为空';
				} else {
					this.errors.name = '';
				}
			},

			// 实时验证手机号格式是否正确
			validatePhone(e) {
				const phoneRegex = /^1[3-9]\d{9}$/; // 简单手机号正则
				if (!this.form.phone.trim()) {
					this.errors.phone = '手机号码不能为空';
				} else if (!phoneRegex.test(this.form.phone)) {
					this.errors.phone = '手机号码格式不正确';
				} else {
					this.errors.phone = '';
				}
			},

			// 实时验证详细地址是否为空
			validateAddress(e) {
				if (!this.form.address.trim()) {
					this.errors.address = '详细地址不能为空';
				} else {
					this.errors.address = '';
				}
			},

			validatePicker() {

				if (!this.userAddress.province || !this.userAddress.city || !this.userAddress.area) {
					this.errors.userAddress = '详细地址不能为空';
				} else {
					this.errors.userAddress = '';
				}
			},


			// 表单提交前的完整验证
			validateForm() {
				// this.validateName();
				this.validatePhone();
				this.validateAddress();
				this.validatePicker();

				if (this.errors.name || this.errors.phone || this.errors.address) {
					uni.showToast({
						title: '请检查表单信息',
						icon: 'none'
					});
					return false;
				}
				if (!this.userAddress.province || !this.userAddress.city || !this.userAddress.area) {
					uni.showToast({
						title: '请选择所在地区',
						icon: 'none'
					});
					return false;
				}
				return true;
			},
			async addAddress() {

				if (!this.validateForm()) return; // 验证失败则停止提交

                //兼容添加和编辑
				
				if(!this.form.city){
					this.form.city =  this.getAddressText()
				}
				let response = '';
				if(this.id){
					response = await this.$api.editAddress(this.form)
				}else{
					response = await this.$api.addAddress(this.form)
				}
				
				
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/address/address'
					});
				}, 1000)
			},
			setDefault() {},
			showRegionPicker() {
				this.show = true;
			},
			cityChange(e) {
				console.log(e)
				this.address = e.province.label + '-' + e.city.label + '-' + e.area.label

			},
			pickerCancel() {
				//隐藏联动展示框
				this.show = false;
				//重置联动数据为初始状态
				this.$refs.uPicker.setIndexs([0, 0, 0], true);
				this.$refs.uPicker.setColumnValues(0, areaList);
				this.$refs.uPicker.setColumnValues(1, areaList[0].cities);
				this.$refs.uPicker.setColumnValues(2, areaList[0].cities[0].districts);

			},
			//三级联动框滑动选择后触发的事件
			changeHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					indexs,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
				if (columnIndex === 0) {
					// picker为选择器this实例，变化第二列对应的选项
					picker.setColumnValues(1, areaList[index].cities)
					picker.setColumnValues(2, areaList[indexs[0]].cities[0].districts)
				} else if (columnIndex === 1) {
					// picker为选择器this实例，变化第三列对应的选项
					picker.setColumnValues(2, areaList[indexs[0]].cities[indexs[1]].districts)
				}
			},
			// 点击确定事件,回调参数为包含columnIndex、value、values
			confirm(e) {
				console.log('confirm', e)
				//省
				this.userAddress.province = e.value[0].name;
				//市
				this.userAddress.city = e.value[1].name;
				//区
				this.userAddress.area = e.value[2].name;
				//区域代码
				this.userAddress.regionId = e.value[2].id;
				
				//城市
				this.city = this.userAddress.province + '/' + this.userAddress.city + '/' + this.userAddress.area;
				
				this.pickerCancel();
			},
		}
	};
</script>

<style lang="scss" scoped>
	.tags {
		width: 140rpx;
		padding: 16rpx 8rpx;
		border: solid 2rpx #ddd;
		text-align: center;
		border-radius: 50rpx;
		margin: 0 10rpx 20rpx;
		display: flex;
		font-size: 28rpx;
		align-items: center;
		justify-content: center;
		color: #666;
		line-height: 1;
		cursor: pointer;
	}

	/* 选中状态 */
	.tags.active {
		background-color: red;
		color: #fff !important; //优先级
	}

	.error_text {
		color: red;
		text-align: center;
	}

	/deep/ .line {
		color: $u-light-color;
		font-size: 28rpx;
	}

	.wrap {
		background-color: #f2f2f2;

		.top {
			background-color: #ffffff;
			border-top: solid 2rpx $u-border-color;
			padding: 22rpx;

			.item {
				display: flex;
				font-size: 32rpx;
				line-height: 100rpx;
				align-items: center;
				border-bottom: solid 2rpx $u-border-color;

				.left {
					width: 180rpx;
				}

				input {
					text-align: left;
				}
			}

			.address {
				padding: 20rpx 0;

				textarea {
					// width: 100%;
					height: 150rpx;
					background-color: #f7f7f7;
					line-height: 60rpx;
					margin: 40rpx auto;
					padding: 20rpx;
				}
			}

			.site-clipboard {
				padding-right: 40rpx;

				textarea {
					// width: 100%;
					height: 150rpx;
					background-color: #f7f7f7;
					line-height: 60rpx;
					margin: 40rpx auto;
					padding: 20rpx;
				}

				.clipboard {
					display: flex;
					justify-content: center;
					align-items: center;
					font-size: 26rpx;
					color: $u-tips-color;
					height: 80rpx;

					.icon {
						margin-top: 6rpx;
						margin-left: 10rpx;
					}
				}
			}
		}

		.bottom {
			margin-top: 20rpx;
			padding: 40rpx;
			padding-right: 0;
			background-color: #ffffff;
			font-size: 28rpx;

			.tag {
				display: flex;

				.left {
					width: 160rpx;
				}

				.right {
					display: flex;
					flex-wrap: wrap;

					.tags {
						width: 140rpx;
						padding: 16rpx 8rpx;
						border: solid 2rpx $u-border-color;
						text-align: center;
						border-radius: 50rpx;
						margin: 0 10rpx 20rpx;
						display: flex;
						font-size: 28rpx;
						align-items: center;
						justify-content: center;
						color: $u-content-color;
						line-height: 1;
					}

					.plus {
						//padding: 10rpx 0;
					}
				}
			}

			.default {
				margin-top: 50rpx;
				display: flex;
				justify-content: space-between;
				border-bottom: solid 2rpx $u-border-color;
				line-height: 64rpx;

				.tips {
					font-size: 24rpx;
				}

				.right {}
			}
		}
	}

	.addSite {
		display: flex;
		justify-content: space-around;
		width: 600rpx;
		line-height: 100rpx;
		position: absolute;
		bottom: 30rpx;
		left: 80rpx;
		background-color: red;
		border-radius: 60rpx;
		font-size: 30rpx;

		.add {
			display: flex;
			align-items: center;
			color: #ffffff;

			.icon {
				margin-right: 10rpx;
			}
		}
	}
</style>